package com.md.common.utils;

import org.apache.commons.collections.CollectionUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class ListUtils extends org.apache.commons.collections.ListUtils {
	
	/**
	 * 从list中获取指定索引位置的元素，如果索引超出界限则返回null
	 * @param list 数据源集合
	 * @param index 所以位置
	 * @return 返回对应索引位置的元素，如果超出界限则返回null，不会抛出IndexOutOfBoundException
	 */
	public static <T> T getOrNullWhenOutOfBound(List<T> list, int index) {
		if (index >= list.size()){
			return null;
		}
		return list.get(index);
	}

	/**
	 * 分割集合为多个指定大小的子集合
	 *
	 * @param c
	 *            源集合数据
	 * @param limit
	 *            分段大小
	 * @return
	 */
	public static <T> List<List<T>> splitCollection(List<T> c, int limit) {
		if (CollectionUtils.isEmpty(c))
			return new ArrayList<>();
		List<List<T>> all = new ArrayList<>();
		if (c.size() <= limit) {
			all.add(c);
			return all;
		}

		int from = 0;
		for (int to = limit, size = c.size(); to < size; to += limit) {
			all.add(c.subList(from, to));
			from += limit;
		}
		all.add(c.subList(from, c.size()));
		return all;
	}

	/**
	 * 截取List
	 * @param c 源List数据
	 * @param fromIndex 其实索引
	 * @param toIndex 结束索引
	 * @return
	 */
	public static <T> List<T> subList(List<T> c, int fromIndex, int toIndex) {
		if (CollectionUtils.isEmpty(c))
			return new ArrayList<>();
		if (fromIndex < 0 || fromIndex >= c.size())
			fromIndex = 0;
		if (toIndex > c.size() || toIndex < fromIndex)
			toIndex = c.size();
		return c.subList(fromIndex, toIndex);
	}

	/**
	 * 往集合中添加元素
	 * @param collect 总集合
	 * @param others 待追加的元素
	 */
	public static <T> void addAll(Collection<T> collect, Collection<T> others) {
		if (collect == null || others == null)
			return;
		collect.addAll(others);
	}

	public static <T> List<List<T>> averageSplitCollection(List<T> c, int segment) {
		if (CollectionUtils.isEmpty(c))
			return new ArrayList<>();
		List<List<T>> all = new ArrayList<>();
		if (c.size() < segment) {
			segment = c.size();
		}
		int segmentSize = c.size() % segment == 0 ? c.size() / segment : (c.size() + segment) / segment;
		int from = 0;
		for (int to = segmentSize, size = c.size(); to < size; to += segmentSize) {
			all.add(c.subList(from, to));
			from += segmentSize;
		}
		all.add(c.subList(from, c.size()));
		return all;
	}

}
